home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / fractions.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  18KB  |  494 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Rational, infinite-precision, real numbers.'''
  5. from __future__ import division
  6. import math
  7. import numbers
  8. import operator
  9. import re
  10. __all__ = [
  11.     'Fraction',
  12.     'gcd']
  13. Rational = numbers.Rational
  14.  
  15. def gcd(a, b):
  16.     '''Calculate the Greatest Common Divisor of a and b.
  17.  
  18.     Unless b==0, the result will have the same sign as b (so that when
  19.     b is divided by it, the result comes out positive).
  20.     '''
  21.     while b:
  22.         a = b
  23.         b = a % b
  24.     return a
  25.  
  26. _RATIONAL_FORMAT = re.compile('\n    \\A\\s*                      # optional whitespace at the start, then\n    (?P<sign>[-+]?)            # an optional sign, then\n    (?=\\d|\\.\\d)                # lookahead for digit or .digit\n    (?P<num>\\d*)               # numerator (possibly empty)\n    (?:                        # followed by an optional\n       /(?P<denom>\\d+)         # / and denominator\n    |                          # or\n       \\.(?P<decimal>\\d*)      # decimal point and fractional part\n    )?\n    \\s*\\Z                      # and optional whitespace to finish\n', re.VERBOSE)
  27.  
  28. class Fraction(Rational):
  29.     """This class implements rational numbers.
  30.  
  31.     Fraction(8, 6) will produce a rational number equivalent to
  32.     4/3. Both arguments must be Integral. The numerator defaults to 0
  33.     and the denominator defaults to 1 so that Fraction(3) == 3 and
  34.     Fraction() == 0.
  35.  
  36.     Fractions can also be constructed from strings of the form
  37.     '[-+]?[0-9]+((/|.)[0-9]+)?', optionally surrounded by spaces.
  38.  
  39.     """
  40.     __slots__ = ('_numerator', '_denominator')
  41.     
  42.     def __new__(cls, numerator = 0, denominator = 1):
  43.         """Constructs a Fraction.
  44.  
  45.         Takes a string like '3/2' or '1.5', another Fraction, or a
  46.         numerator/denominator pair.
  47.  
  48.         """
  49.         self = super(Fraction, cls).__new__(cls)
  50.         if type(numerator) not in (int, long) and denominator == 1:
  51.             if isinstance(numerator, basestring):
  52.                 input = numerator
  53.                 m = _RATIONAL_FORMAT.match(input)
  54.                 if m is None:
  55.                     raise ValueError('Invalid literal for Fraction: %r' % input)
  56.                 m is None
  57.                 numerator = m.group('num')
  58.                 decimal = m.group('decimal')
  59.                 if decimal:
  60.                     numerator = int(numerator + decimal)
  61.                     denominator = 10 ** len(decimal)
  62.                 else:
  63.                     numerator = int(numerator)
  64.                     if not m.group('denom'):
  65.                         pass
  66.                     denominator = int(1)
  67.                 if m.group('sign') == '-':
  68.                     numerator = -numerator
  69.                 
  70.             elif isinstance(numerator, Rational):
  71.                 other_rational = numerator
  72.                 numerator = other_rational.numerator
  73.                 denominator = other_rational.denominator
  74.             
  75.         
  76.         if denominator == 0:
  77.             raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
  78.         denominator == 0
  79.         numerator = operator.index(numerator)
  80.         denominator = operator.index(denominator)
  81.         g = gcd(numerator, denominator)
  82.         self._numerator = numerator // g
  83.         self._denominator = denominator // g
  84.         return self
  85.  
  86.     
  87.     def from_float(cls, f):
  88.         '''Converts a finite float to a rational number, exactly.
  89.  
  90.         Beware that Fraction.from_float(0.3) != Fraction(3, 10).
  91.  
  92.         '''
  93.         if isinstance(f, numbers.Integral):
  94.             return cls(f)
  95.         if not isinstance(f, float):
  96.             raise TypeError('%s.from_float() only takes floats, not %r (%s)' % (cls.__name__, f, type(f).__name__))
  97.         isinstance(f, float)
  98.         if math.isnan(f) or math.isinf(f):
  99.             raise TypeError('Cannot convert %r to %s.' % (f, cls.__name__))
  100.         math.isinf(f)
  101.         return cls(*f.as_integer_ratio())
  102.  
  103.     from_float = classmethod(from_float)
  104.     
  105.     def from_decimal(cls, dec):
  106.         '''Converts a finite Decimal instance to a rational number, exactly.'''
  107.         Decimal = Decimal
  108.         import decimal
  109.         if isinstance(dec, numbers.Integral):
  110.             dec = Decimal(int(dec))
  111.         elif not isinstance(dec, Decimal):
  112.             raise TypeError('%s.from_decimal() only takes Decimals, not %r (%s)' % (cls.__name__, dec, type(dec).__name__))
  113.         
  114.         if not dec.is_finite():
  115.             raise TypeError('Cannot convert %s to %s.' % (dec, cls.__name__))
  116.         dec.is_finite()
  117.         (sign, digits, exp) = dec.as_tuple()
  118.         digits = int(''.join(map(str, digits)))
  119.         if sign:
  120.             digits = -digits
  121.         
  122.         if exp >= 0:
  123.             return cls(digits * 10 ** exp)
  124.         return cls(digits, 10 ** (-exp))
  125.  
  126.     from_decimal = classmethod(from_decimal)
  127.     
  128.     def limit_denominator(self, max_denominator = 1000000):
  129.         """Closest Fraction to self with denominator at most max_denominator.
  130.  
  131.         >>> Fraction('3.141592653589793').limit_denominator(10)
  132.         Fraction(22, 7)
  133.         >>> Fraction('3.141592653589793').limit_denominator(100)
  134.         Fraction(311, 99)
  135.         >>> Fraction(1234, 5678).limit_denominator(10000)
  136.         Fraction(1234, 5678)
  137.  
  138.         """
  139.         if max_denominator < 1:
  140.             raise ValueError('max_denominator should be at least 1')
  141.         max_denominator < 1
  142.         if self._denominator <= max_denominator:
  143.             return Fraction(self)
  144.         (p0, q0, p1, q1) = (0, 1, 1, 0)
  145.         n = self._numerator
  146.         d = self._denominator
  147.         while True:
  148.             a = n // d
  149.             q2 = q0 + a * q1
  150.             if q2 > max_denominator:
  151.                 break
  152.             
  153.             (p0, q0, p1, q1) = (p1, q1, p0 + a * p1, q2)
  154.             n = d
  155.             d = n - a * d
  156.         k = (max_denominator - q0) // q1
  157.         bound1 = Fraction(p0 + k * p1, q0 + k * q1)
  158.         bound2 = Fraction(p1, q1)
  159.         if abs(bound2 - self) <= abs(bound1 - self):
  160.             return bound2
  161.         return bound1
  162.  
  163.     
  164.     def numerator(a):
  165.         return a._numerator
  166.  
  167.     numerator = property(numerator)
  168.     
  169.     def denominator(a):
  170.         return a._denominator
  171.  
  172.     denominator = property(denominator)
  173.     
  174.     def __repr__(self):
  175.         '''repr(self)'''
  176.         return 'Fraction(%s, %s)' % (self._numerator, self._denominator)
  177.  
  178.     
  179.     def __str__(self):
  180.         '''str(self)'''
  181.         if self._denominator == 1:
  182.             return str(self._numerator)
  183.         return '%s/%s' % (self._numerator, self._denominator)
  184.  
  185.     
  186.     def _operator_fallbacks(monomorphic_operator, fallback_operator):
  187.         '''Generates forward and reverse operators given a purely-rational
  188.         operator and a function from the operator module.
  189.  
  190.         Use this like:
  191.         __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
  192.  
  193.         In general, we want to implement the arithmetic operations so
  194.         that mixed-mode operations either call an implementation whose
  195.         author knew about the types of both arguments, or convert both
  196.         to the nearest built in type and do the operation there. In
  197.         Fraction, that means that we define __add__ and __radd__ as:
  198.  
  199.             def __add__(self, other):
  200.                 # Both types have numerators/denominator attributes,
  201.                 # so do the operation directly
  202.                 if isinstance(other, (int, long, Fraction)):
  203.                     return Fraction(self.numerator * other.denominator +
  204.                                     other.numerator * self.denominator,
  205.                                     self.denominator * other.denominator)
  206.                 # float and complex don\'t have those operations, but we
  207.                 # know about those types, so special case them.
  208.                 elif isinstance(other, float):
  209.                     return float(self) + other
  210.                 elif isinstance(other, complex):
  211.                     return complex(self) + other
  212.                 # Let the other type take over.
  213.                 return NotImplemented
  214.  
  215.             def __radd__(self, other):
  216.                 # radd handles more types than add because there\'s
  217.                 # nothing left to fall back to.
  218.                 if isinstance(other, Rational):
  219.                     return Fraction(self.numerator * other.denominator +
  220.                                     other.numerator * self.denominator,
  221.                                     self.denominator * other.denominator)
  222.                 elif isinstance(other, Real):
  223.                     return float(other) + float(self)
  224.                 elif isinstance(other, Complex):
  225.                     return complex(other) + complex(self)
  226.                 return NotImplemented
  227.  
  228.  
  229.         There are 5 different cases for a mixed-type addition on
  230.         Fraction. I\'ll refer to all of the above code that doesn\'t
  231.         refer to Fraction, float, or complex as "boilerplate". \'r\'
  232.         will be an instance of Fraction, which is a subtype of
  233.         Rational (r : Fraction <: Rational), and b : B <:
  234.         Complex. The first three involve \'r + b\':
  235.  
  236.             1. If B <: Fraction, int, float, or complex, we handle
  237.                that specially, and all is well.
  238.             2. If Fraction falls back to the boilerplate code, and it
  239.                were to return a value from __add__, we\'d miss the
  240.                possibility that B defines a more intelligent __radd__,
  241.                so the boilerplate should return NotImplemented from
  242.                __add__. In particular, we don\'t handle Rational
  243.                here, even though we could get an exact answer, in case
  244.                the other type wants to do something special.
  245.             3. If B <: Fraction, Python tries B.__radd__ before
  246.                Fraction.__add__. This is ok, because it was
  247.                implemented with knowledge of Fraction, so it can
  248.                handle those instances before delegating to Real or
  249.                Complex.
  250.  
  251.         The next two situations describe \'b + r\'. We assume that b
  252.         didn\'t know about Fraction in its implementation, and that it
  253.         uses similar boilerplate code:
  254.  
  255.             4. If B <: Rational, then __radd_ converts both to the
  256.                builtin rational type (hey look, that\'s us) and
  257.                proceeds.
  258.             5. Otherwise, __radd__ tries to find the nearest common
  259.                base ABC, and fall back to its builtin type. Since this
  260.                class doesn\'t subclass a concrete type, there\'s no
  261.                implementation to fall back to, so we need to try as
  262.                hard as possible to return an actual value, or the user
  263.                will get a TypeError.
  264.  
  265.         '''
  266.         
  267.         def forward(a, b):
  268.             if isinstance(b, (int, long, Fraction)):
  269.                 return monomorphic_operator(a, b)
  270.             if isinstance(b, float):
  271.                 return fallback_operator(float(a), b)
  272.             if isinstance(b, complex):
  273.                 return fallback_operator(complex(a), b)
  274.             return NotImplemented
  275.  
  276.         forward.__name__ = '__' + fallback_operator.__name__ + '__'
  277.         forward.__doc__ = monomorphic_operator.__doc__
  278.         
  279.         def reverse(b, a):
  280.             if isinstance(a, Rational):
  281.                 return monomorphic_operator(a, b)
  282.             if isinstance(a, numbers.Real):
  283.                 return fallback_operator(float(a), float(b))
  284.             if isinstance(a, numbers.Complex):
  285.                 return fallback_operator(complex(a), complex(b))
  286.             return NotImplemented
  287.  
  288.         reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
  289.         reverse.__doc__ = monomorphic_operator.__doc__
  290.         return (forward, reverse)
  291.  
  292.     
  293.     def _add(a, b):
  294.         '''a + b'''
  295.         return Fraction(a.numerator * b.denominator + b.numerator * a.denominator, a.denominator * b.denominator)
  296.  
  297.     (__add__, __radd__) = _operator_fallbacks(_add, operator.add)
  298.     
  299.     def _sub(a, b):
  300.         '''a - b'''
  301.         return Fraction(a.numerator * b.denominator - b.numerator * a.denominator, a.denominator * b.denominator)
  302.  
  303.     (__sub__, __rsub__) = _operator_fallbacks(_sub, operator.sub)
  304.     
  305.     def _mul(a, b):
  306.         '''a * b'''
  307.         return Fraction(a.numerator * b.numerator, a.denominator * b.denominator)
  308.  
  309.     (__mul__, __rmul__) = _operator_fallbacks(_mul, operator.mul)
  310.     
  311.     def _div(a, b):
  312.         '''a / b'''
  313.         return Fraction(a.numerator * b.denominator, a.denominator * b.numerator)
  314.  
  315.     (__truediv__, __rtruediv__) = _operator_fallbacks(_div, operator.truediv)
  316.     (__div__, __rdiv__) = _operator_fallbacks(_div, operator.div)
  317.     
  318.     def __floordiv__(a, b):
  319.         '''a // b'''
  320.         div = a / b
  321.         if isinstance(div, Rational):
  322.             return div.numerator // div.denominator
  323.         return math.floor(div)
  324.  
  325.     
  326.     def __rfloordiv__(b, a):
  327.         '''a // b'''
  328.         div = a / b
  329.         if isinstance(div, Rational):
  330.             return div.numerator // div.denominator
  331.         return math.floor(div)
  332.  
  333.     
  334.     def __mod__(a, b):
  335.         '''a % b'''
  336.         div = a // b
  337.         return a - b * div
  338.  
  339.     
  340.     def __rmod__(b, a):
  341.         '''a % b'''
  342.         div = a // b
  343.         return a - b * div
  344.  
  345.     
  346.     def __pow__(a, b):
  347.         '''a ** b
  348.  
  349.         If b is not an integer, the result will be a float or complex
  350.         since roots are generally irrational. If b is an integer, the
  351.         result will be rational.
  352.  
  353.         '''
  354.         if isinstance(b, Rational):
  355.             if b.denominator == 1:
  356.                 power = b.numerator
  357.                 if power >= 0:
  358.                     return Fraction(a._numerator ** power, a._denominator ** power)
  359.                 return Fraction(a._denominator ** (-power), a._numerator ** (-power))
  360.             b.denominator == 1
  361.             return float(a) ** float(b)
  362.         isinstance(b, Rational)
  363.         return float(a) ** b
  364.  
  365.     
  366.     def __rpow__(b, a):
  367.         '''a ** b'''
  368.         if b._denominator == 1 and b._numerator >= 0:
  369.             return a ** b._numerator
  370.         if isinstance(a, Rational):
  371.             return Fraction(a.numerator, a.denominator) ** b
  372.         if b._denominator == 1:
  373.             return a ** b._numerator
  374.         return a ** float(b)
  375.  
  376.     
  377.     def __pos__(a):
  378.         '''+a: Coerces a subclass instance to Fraction'''
  379.         return Fraction(a._numerator, a._denominator)
  380.  
  381.     
  382.     def __neg__(a):
  383.         '''-a'''
  384.         return Fraction(-(a._numerator), a._denominator)
  385.  
  386.     
  387.     def __abs__(a):
  388.         '''abs(a)'''
  389.         return Fraction(abs(a._numerator), a._denominator)
  390.  
  391.     
  392.     def __trunc__(a):
  393.         '''trunc(a)'''
  394.         if a._numerator < 0:
  395.             return -(-(a._numerator) // a._denominator)
  396.         return a._numerator // a._denominator
  397.  
  398.     
  399.     def __hash__(self):
  400.         '''hash(self)
  401.  
  402.         Tricky because values that are exactly representable as a
  403.         float must have the same hash as that float.
  404.  
  405.         '''
  406.         if self._denominator == 1:
  407.             return hash(self._numerator)
  408.         if self == float(self):
  409.             return hash(float(self))
  410.         return hash((self._numerator, self._denominator))
  411.  
  412.     
  413.     def __eq__(a, b):
  414.         '''a == b'''
  415.         if isinstance(b, Rational):
  416.             if a._numerator == b.numerator:
  417.                 pass
  418.             return a._denominator == b.denominator
  419.         if isinstance(b, numbers.Complex) and b.imag == 0:
  420.             b = b.real
  421.         
  422.         if isinstance(b, float):
  423.             return a == a.from_float(b)
  424.         return float(a) == b
  425.  
  426.     
  427.     def _subtractAndCompareToZero(a, b, op):
  428.         """Helper function for comparison operators.
  429.  
  430.         Subtracts b from a, exactly if possible, and compares the
  431.         result with 0 using op, in such a way that the comparison
  432.         won't recurse. If the difference raises a TypeError, returns
  433.         NotImplemented instead.
  434.  
  435.         """
  436.         if isinstance(b, numbers.Complex) and b.imag == 0:
  437.             b = b.real
  438.         
  439.         if isinstance(b, float):
  440.             b = a.from_float(b)
  441.         
  442.         
  443.         try:
  444.             diff = a - b
  445.         except TypeError:
  446.             return NotImplemented
  447.  
  448.         if isinstance(diff, Rational):
  449.             return op(diff.numerator, 0)
  450.         return op(diff, 0)
  451.  
  452.     
  453.     def __lt__(a, b):
  454.         '''a < b'''
  455.         return a._subtractAndCompareToZero(b, operator.lt)
  456.  
  457.     
  458.     def __gt__(a, b):
  459.         '''a > b'''
  460.         return a._subtractAndCompareToZero(b, operator.gt)
  461.  
  462.     
  463.     def __le__(a, b):
  464.         '''a <= b'''
  465.         return a._subtractAndCompareToZero(b, operator.le)
  466.  
  467.     
  468.     def __ge__(a, b):
  469.         '''a >= b'''
  470.         return a._subtractAndCompareToZero(b, operator.ge)
  471.  
  472.     
  473.     def __nonzero__(a):
  474.         '''a != 0'''
  475.         return a._numerator != 0
  476.  
  477.     
  478.     def __reduce__(self):
  479.         return (self.__class__, (str(self),))
  480.  
  481.     
  482.     def __copy__(self):
  483.         if type(self) == Fraction:
  484.             return self
  485.         return self.__class__(self._numerator, self._denominator)
  486.  
  487.     
  488.     def __deepcopy__(self, memo):
  489.         if type(self) == Fraction:
  490.             return self
  491.         return self.__class__(self._numerator, self._denominator)
  492.  
  493.  
  494.